package com.pan.test.udp.example01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Receiver01 {

    /**
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(11451);
        //UDP 每个包最大只能64k
        byte[] buf = new byte[1024];
        //udp收发都是这样的包DatagramPacket，字节流什么的都封装起来了
        DatagramPacket datagramPacket = new DatagramPacket(buf,buf.length);
        //如果该接口收到数据就会放到Packet，如果没有就会阻塞
        datagramSocket.receive(datagramPacket);
        //拆包
        byte[] data = datagramPacket.getData();
        int len = datagramPacket.getLength();
        System.out.println("接收: "+new String(data,0,len));



        //回复
        String msg = "好的，我也启动";
        datagramPacket.setLength(msg.getBytes().length);
        datagramPacket.setData(msg.getBytes());
        datagramPacket.setAddress(InetAddress.getByName("192.168.31.43"));
        datagramPacket.setPort(11452);
        datagramSocket.send(datagramPacket);


        datagramSocket.close();
    }


}
